package com.tristia.service.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tristia.entity.Cd;
import com.tristia.service.CdService;

@Service("cdService")
public class CdServiceJpa implements CdService {

	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}
	
	@Transactional(readOnly = true)
	public Cd getById(long id) {
		// TODO Auto-generated method stub
		return entityManager.find(Cd.class, id);
	}
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Cd> getAll() {
		Query query = entityManager.createNamedQuery("Cd.findAll");
		List<Cd> cds = null;
		cds = query.getResultList();
		return cds;
	}

	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean save(Cd cd) {
		
		entityManager.persist(cd);
		entityManager.flush();
		
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean update(Cd cd) {
		entityManager.merge(cd);
		entityManager.flush();
		return true;
	}
	@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
	public boolean delete(Cd cd) {
		cd = entityManager.getReference(Cd.class, cd.getId());
		if (cd == null)
			return false;
		entityManager.remove(cd);
		entityManager.flush();
		return true;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public Cd findCd(Cd cd) {
		Cd result = null;
		Query queryFindCd = entityManager.createNamedQuery("Cd.findCd");
		queryFindCd.setParameter("title", cd.getTitle());
		queryFindCd.setParameter("author", cd.getAuthor());
		List<Cd> cds = queryFindCd.getResultList();
		if(cds.size() > 0) {
			result = cds.get(0);
		}
		return result;
	}
}
